﻿/*
The MIT License (MIT)
Copyright (c) 2013 kaveh.shahbazian@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using Microsoft.VisualBasic.FileIO;

namespace Buddy
{
    public static partial class Fx
    {
        /// <summary>
        /// returns a not null string
        /// </summary>
        /// <param name="oj"></param>
        /// <returns></returns>
        public static string Text(this object oj) { return (oj ?? string.Empty).ToString(); }

        /// <summary>
        /// returns !string.IsNullOrWhiteSpace(arg)
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public static bool IsSupplied(this string arg) { return !string.IsNullOrWhiteSpace(arg); }

        /// <summary>
        /// returns !object.Equals(t, default(T))
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool IsSupplied<T>(this T t) { return !object.Equals(t, default(T)); }

        public static R Pipe<T, R>(this T o, Func<T, R> func)
        {
            if (func == null) throw new ArgumentNullException("func", "'func' can not be null.");
            T buffer = o;
            return func(buffer);
        }

        public static T Pipe<T>(this T o, Action<T> action)
        {
            if (action == null) throw new ArgumentNullException("action", "'action' can not be null.");
            T buffer = o;
            action(buffer);
            return buffer;
        }

        //public static string ToXml<T>(this T objectToSerialize) where T : class, new()
        //{
        //    //1
        //    var result = new StringBuilder();

        //    //2
        //    using (var sw = new StringWriter(result))
        //    {
        //        try
        //        {
        //            var xs = new XmlSerializer(typeof(T));
        //            xs.Serialize(sw, objectToSerialize);
        //        }
        //        finally
        //        {
        //            sw.Close();
        //        }
        //    }

        //    //3
        //    return result.ToString();
        //}

        //public static T FromXml<T>(this string objectSerializedXML) where T : class, new()
        //{
        //    //1
        //    T result;

        //    //2
        //    using (var sr = new StringReader(objectSerializedXML))
        //    {
        //        try
        //        {
        //            var xs = new XmlSerializer(typeof(T));
        //            result = xs.Deserialize(sr) as T;
        //        }
        //        finally
        //        {
        //            sr.Close();
        //        }
        //    }

        //    //3
        //    return result;
        //}

        //public static string ToJson<T>(this T t)
        //{
        //    var json_serializer = new JavaScriptSerializer();
        //    return json_serializer.Serialize(t);
        //}

        //public static T FromJson<T>(this string json)
        //{
        //    var json_serializer = new JavaScriptSerializer();
        //    return json_serializer.Deserialize<T>(json);
        //}

        public static IEnumerable<string> Lines(this StreamReader reader)
        {
            string line = null;
            while ((line = reader.ReadLine()) != null) yield return line;
        }

        static string PutInQuotes(object o) { return string.Format("\"{0}\"", o); }
        public static void WriteRecord(this StreamWriter writer, string delimiter, params object[] fields)
        {
            writer.WriteLine(string.Join(delimiter, (from o in fields
                                                     let str = (o ?? string.Empty).ToString().Replace("\"", "\"\"")
                                                     select (str.Contains(delimiter) || str.Contains("\"")) ? PutInQuotes(str) : str).ToArray()));
        }

        public static IEnumerable<string[]> Records(this TextFieldParser csv) { return csv.Records(true); }

        public static IEnumerable<string[]> Records(this TextFieldParser csv, bool ignoreInvalidRecords)
        {
            string[] record = null;
            while (!csv.EndOfData)
            {
                record = null;

                if (ignoreInvalidRecords)
                {
                    try { record = csv.ReadFields(); }
                    catch { }
                }
                else record = csv.ReadFields();

                if (record != null) yield return record;
            }
        }

        public static T ToStruct<T>(this byte[] bytes) where T : struct
        {
            T st = default(T);

            int size = Marshal.SizeOf(st);
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.Copy(bytes, 0, ptr, size);

            st = (T)Marshal.PtrToStructure(ptr, typeof(T));
            Marshal.FreeHGlobal(ptr);

            return st;
        }

        public static byte[] FromStruct<T>(this T st) where T : struct
        {
            int size = Marshal.SizeOf(st);
            byte[] bytes = new byte[size];
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.StructureToPtr(st, ptr, true);
            Marshal.Copy(ptr, bytes, 0, size);
            Marshal.FreeHGlobal(ptr);

            return bytes;
        }

        public static string BinaryText(this byte[] bytes)
        {
            var data = new StringBuilder();
            foreach (var b in bytes)
            {
                data.Append(b.ToString("X2"));
                data.Append(" ");
            }
            return data.ToString().Trim();
        }

        public static void WriteLine(this TraceSource source, object o)
        {
            var str = (o ?? string.Empty).ToString();

            if (source.Listeners == null || source.Listeners.Count == 0) throw new InvalidOperationException(string.Format("TraceSource named {0} has no listeners", source.Name));

            foreach (TraceListener listener in source.Listeners)
                listener.WriteLine(str);
        }
    }
}
